import React, { useState, useEffect } from 'react'
import { Card, Button, Form, Input, DatePicker, Table, Space, message, Spin, Popconfirm, Upload } from 'antd'
import './index.less'
import { useStore } from '../../store'
import moment from 'moment'
import { UploadOutlined } from '@ant-design/icons'


type LayoutType = Parameters<typeof Form>[0]['layout'];
const { RangePicker } = DatePicker;

const TemplateTable = (props: any) => {
    const { userStore } = useStore()
    const { tableDate, getTableData } = props
    const pagination = {
        hideOnSinglePage: true,
    }

    const downloadFile = async (e: any) => {
        console.log(e);
        try {
            const res = await userStore.downloadTemplate({ object_name: e.name })
            const url = window.URL.createObjectURL(new Blob([res]))
            const link = document.createElement('a')
            link.href = url
            link.setAttribute('download', e.name)
            document.body.appendChild(link)
            link.click()
            message.success(`下载${e.name}成功`)

        } catch (error) {

        }
    }

    const deleteFile = async (e: any) => {
        try {
            const { code, msg, data } = await userStore.deleteTemplate({ object_name: e.name })
            if (code === 200) {
                getTableData()
                message.success(msg)
            } else {
                message.error(msg)
            }
        } catch (error) {
            message.error("网络错误")

        }
    }

    const columns: any = [
        {
            title: '模板上传时间',
            dataIndex: 'date',
            key: 'date',
        },
        {
            title: '文件名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_: any, record: any) => (
                <Space size="middle" >
                    <a target="_blank" onClick={(e) => { downloadFile(record) }}>
                        下载
                    </a>
                    <Popconfirm
                        placement="topLeft"
                        title="此操作不可逆,确认删除此数据"
                        onConfirm={() => { deleteFile(record) }}
                    >
                        <a target="_blank">
                            删除
                        </a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <Table dataSource={tableDate} columns={columns} className="templateTable" pagination={pagination} />

    )
}

const Home: React.FC = () => {
    const [form] = Form.useForm();
    const [formLayout, setFormLayout] = useState<LayoutType>('inline');
    const [loading, setLoading] = useState(false)
    const { userStore } = useStore()

    const [tableDate, setTableData] = useState([])
    const [searchObj, setSearchObj] = useState()

    useEffect(() => {
        getTableData()
    }, [searchObj])


    const getTableData = async () => {
        try {
            const { code, msg, data } = await userStore.getTemplate(searchObj)
            if (code == 200) {
                data.map((res: any, index: number) => {
                    const momentObj = moment.utc(res.date);
                    const dateStr = momentObj.format("YYYY-MM-DD HH:MM:SS");
                    data[index].date = dateStr
                })
                console.log(code, msg, data);
                setTableData(data)
            } else {
                message.error(msg)
            }
        } catch (error) {
            message.error("网络错误请重试")
        }
    }


    const onFinish = async (value: any) => {
        if (value.rangtime) {
            value.start_date = moment(value.rangtime[0]).format("YYYY-MM-DD HH:MM:SS")
            value.end_date = moment(value.rangtime[1]).format("YYYY-MM-DD HH:MM:SS")
            delete value.rangtime
        }
        setSearchObj(value)
    }

    const customRequest = async (option: any) => {
        const formData = new FormData();
        formData.append('file', option.file);
        await userStore.updateTemplate(formData)
        try {
            setLoading(true)
            const { code, msg } = await userStore.updateTemplate(formData)
            if (code == 200) {
                getTableData()
                message.success(msg)
            } else {
                message.error(msg)
            }
        } catch (error) {
            message.error("上传失败")
        } finally {
            setLoading(false)
        }
    }

    return (
        <Spin spinning={loading}>
            <Card>
                <header className='home-header'>
                    <div className='home-left'>
                        <Form
                            layout={formLayout}
                            form={form}
                            initialValues={{ layout: formLayout }}
                            onFinish={onFinish}
                        >
                            <Form.Item label="文件名" name="keyword">
                                <Input placeholder="请输入文件名" />
                            </Form.Item>
                            <Form.Item label="时间筛选" name="rangtime">
                                <RangePicker />
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    搜索
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <Upload customRequest={customRequest} showUploadList={false}>
                        <Button icon={<UploadOutlined />} type="text">上传模板</Button>
                    </Upload>
                </header>
                <TemplateTable tableDate={tableDate} getTableData={getTableData}></TemplateTable>
            </Card>
        </Spin>
    )
}
export default Home
